package com.juzipi.demo.util;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Author juzipi
 * @Date 2021/5/23 15:22
 * @Info 上传图片工具类
 */
public class UploadImageUtils {


    /*
    从请求流中获取流信息
    新建临时文件，用输出流指向这个文件
     */
    public static void saveFile(HttpServletRequest request){
        try {
            ServletInputStream inputStream = request.getInputStream();
            String tempFileName = request.getServletContext().getRealPath("/") + "temp/tempfile.txt";
            //新建一个文件
            File file = new File(tempFileName);
            //用输出流指向这个文件
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            //每次读写10k
            byte[] bytes = new byte[1024 * 10];
            int n = 0;
            while ((n=inputStream.read(bytes)) != -1){
                fileOutputStream.write(bytes,0,n);
            }
            fileOutputStream.close();
            inputStream.close();


        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
